//
//  GQHFreightInfoController.m
//  Xanthium
//
//  Created by GuanQinghao on 08/03/2018.
//  Copyright © 2018 GuanQinghao. All rights reserved.
//

#pragma mark Macro
#import "GQHHeader.h"

#pragma mark Model

#pragma mark Object

#pragma mark View
#import "GQHFreightInfoView.h"
#import "GQHCustomCell.h"

#pragma mark Controller
#import "GQHFreightInfoController.h"
#import "GQHMapController.h"

#pragma mark CocoaPods

#pragma mark ----------Header End----------

@interface GQHFreightInfoController () <GQHFreightInfoViewDelegate>{
    
#pragma mark Data
    
#pragma mark View
    /// 自定义根视图
    GQHFreightInfoView *rootView;
}

@end


@implementation GQHFreightInfoController

#pragma mark --Lifecycle
- (void)loadView {
    DLog();
    
    rootView = [[GQHFreightInfoView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    rootView.qh_delegate = self;
    self.view = rootView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    DLog();
    
    [self loadLocalData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    DLog();
    
    self.qh_titleLabel.text = @"货源详情";
    self.qh_rightButton.hidden = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    if (self.qh_freightModel.qh_offerStatus != NULL && ![self.qh_freightModel.qh_offerStatus isEqualToString:@""] && ![self.qh_freightModel.qh_offerStatus isEqualToString:@"01"])
    {
        [rootView.qh_quoteButton setTitle:@"重新报价" forState:0];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    DLog();
    
}

#pragma mark --Delegate
- (void)qh_quotePrice {
    DLog(@"报价");
    
    [self qh_checkAccessPermissionType:GQHAccessPermissionTypeJunior allowed:^{
        
        [self quotePrice];
    } unallowed:nil];
}

-(void)qh_dialPhoneNumber {
    DLog(@"联系货主");
    
    [self qh_checkAccessPermissionType:GQHAccessPermissionTypeJunior allowed:^{
        
        [self qh_dialWithMobile:_qh_freightModel.qh_posterMobile];
    } unallowed:nil];
}

- (void)qh_checkMap {
    DLog(@"查看地图");
    
    [self qh_checkAccessPermissionType:GQHAccessPermissionTypeJunior allowed:^{
        
        GQHMapController *mapController = [[GQHMapController alloc] init];
        mapController.qh_departureLatitude = _qh_freightModel.qh_departureLatitude;
        mapController.qh_departureLongitude = _qh_freightModel.qh_departureLongitude;
        mapController.qh_destinationLatitude = _qh_freightModel.qh_destinationLatitude;
        mapController.qh_destinationLongitude = _qh_freightModel.qh_destinationLongitude;
        mapController.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:mapController animated:YES];
    } unallowed:nil];
}

- (void)qh_followedOrUnfollowed:(UIButton *)sender {
    DLog(@"关注或取消关注");
    
    [self qh_checkAccessPermissionType:GQHAccessPermissionTypeJunior allowed:^{
        
        [self followedOrUnfollowed];
    } unallowed:nil];
}

#pragma mark --TargetMethod

#pragma mark --PrivateMethod
- (void)loadLocalData {
    
    NSMutableArray *contentArray = [NSMutableArray arrayWithCapacity:20];
    
    // 起始地
    [contentArray qh_safetySetObject:_qh_freightModel.qh_departure atIndex:0];
    
    // 目的地
    [contentArray qh_safetySetObject:_qh_freightModel.qh_destination atIndex:1];
    
    // 估算里程
    [contentArray qh_safetySetObject:[NSString stringWithFormat:@"%@km", _qh_freightModel.qh_mileage] atIndex:2];
    
//    // 货物名称
//    [contentArray qh_safetySetObject:_qh_freightModel.qh_freightName atIndex:3];
//
//    // 货物类型
//    [contentArray qh_safetySetObject:_qh_freightModel.qh_freightType atIndex:4];
    
    // 货物重量
    NSString *weight = [NSString stringWithFormat:@"%@/%.0f吨", _qh_freightModel.qh_freightName, _qh_freightModel.qh_freightWeight];
    [contentArray qh_safetySetObject:weight atIndex:3];
    
//    // 货物体积
//    NSString *volume = [NSString stringWithFormat:@"%.0f",_qh_freightModel.qh_freightVolume];
//    [contentArray qh_safetySetObject:volume atIndex:6];
//
//    // 货物数量
//    NSString *number = [NSString stringWithFormat:@"%.0f",_qh_freightModel.qh_freightNumber];
//    [contentArray qh_safetySetObject:number atIndex:7];
    
    // 货物单价
    NSString *unitPrice = [NSString stringWithFormat:@"%.2f元/吨",_qh_freightModel.qh_freightUnitPrice];
    [contentArray qh_safetySetObject:unitPrice atIndex:4];
    
    // 需求车型
    [contentArray qh_safetySetObject:_qh_freightModel.qh_modelWanted atIndex:5];
    
    // 需求车长
    [contentArray qh_safetySetObject:_qh_freightModel.qh_lengthWanted atIndex:6];
    
    // 装车时间
    [contentArray qh_safetySetObject:_qh_freightModel.qh_loadingTime atIndex:7];
    
    // 备注
    [contentArray qh_safetySetObject:_qh_freightModel.qh_note atIndex:8];
    
    rootView.qh_contentArray = contentArray;
    
    rootView.qh_avatar = _qh_freightModel.qh_posterAvatar;
    rootView.qh_name = _qh_freightModel.qh_posterName;
    rootView.qh_orgName = _qh_freightModel.qh_enterpriseName;
    NSString *score = [NSString stringWithFormat:@"评分: %.2f 分",_qh_freightModel.qh_posterScore];
    rootView.qh_score = score;
    rootView.qh_followed = _qh_freightModel.qh_followed;
    if ([_qh_freightModel.qh_offerStatus isEqualToString:@"01"]) {
        
        [rootView.qh_quoteButton setTitle:@"重新报价" forState:UIControlStateNormal];
    } else {
        
        [rootView.qh_quoteButton setTitle:@"我要报价" forState:UIControlStateNormal];
    }
    [rootView.qh_tableView reloadData];
}

- (void)followedOrUnfollowed {
    
    if (rootView.qh_followed) {
        
        /// 取消关注
        NSDictionary *parameters = @{@"beFocusOn" : _qh_freightModel.qh_posterID,@"focusOnPeople" : USER_GET_ID};
        NSString *URLString = [[NSString qh_APIURLString] stringByAppendingString:@"/buUsersAttention/1/delete"];
        [GQHNetHelper qh_requestGET:URLString parameters:parameters success:^(NSNumber *code, NSString *message, NSDictionary *data) {
            
            if (0 == [code intValue]) {
                
                rootView.qh_followed = NO;
                [rootView.qh_tableView reloadData];
            } else {
                
                [self showToastWithText:message];
            }
        } failure:^(NSError *error) {
            
            NSString *errorString = [NSString stringWithFormat:@"网络出错:%@,code:%ld", error.domain, (long)error.code];
            [self showToastWithText:errorString];
        }];
    } else {
        
        /// 关注
        NSDictionary *parameters = @{@"beFocusOn" : _qh_freightModel.qh_posterID,@"focusOnPeople" : USER_GET_ID};
        NSString *URLString = [[NSString qh_APIURLString] stringByAppendingString:@"/buUsersAttention/1/save"];
        [GQHNetHelper qh_requestGET:URLString parameters:parameters success:^(NSNumber *code, NSString *message, NSDictionary *data) {
            
            if (0 == [code intValue]) {
                
                rootView.qh_followed = YES;
                [rootView.qh_tableView reloadData];
            } else {
                
                [self showToastWithText:message];
            }
        } failure:^(NSError *error) {
            
            NSString *errorString = [NSString stringWithFormat:@"网络出错:%@,code:%ld", error.domain, (long)error.code];
            [self showToastWithText:errorString];
        }];
    }
}

/// 报价
- (void)quotePrice {
    
    [self qh_alertWithTitle:@"报价金额 (元/吨)" message:nil inputHandler:^(UITextField * _Nullable textField) {
        
        textField.placeholder = @"请输入报价金额";
        textField.keyboardType = UIKeyboardTypeDecimalPad;
    } actionHandler:^(UIAlertAction * _Nullable action, UIAlertController * _Nonnull alertController) {
        
        UITextField *inputTextField = alertController.textFields.firstObject;
        
        if (!inputTextField.text) {
            
            [self showToastWithText:@"报价金额不能为空"];
            
            return;
        }
        
        if (!([inputTextField.text qh_isValidDecimal] || [inputTextField.text qh_isOnlyNumber])) {
            
            [self showToastWithText:@"报价金额不是有效的金额格式"];
            
            return;
        }
        
        if (0.0f == [inputTextField.text doubleValue]) {
            
            [self showToastWithText:@"报价金额不能为零"];
            
            return;
        }
        
        if (inputTextField.text.length > 0) {
            
            NSNumber *quote = [NSNumber numberWithDouble:[inputTextField.text doubleValue]];
            NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
            [parameters setObject:USER_GET_ID forKey:@"userId"];
            [parameters setObject:_qh_freightModel.qh_freightID forKey:@"sourcesId"];
            [parameters setObject:quote forKey:@"offer"];
            
            NSString *URLString = [[NSString qh_APIURLString] stringByAppendingString:@"/buQuotationRecord/1/add"];
            [GQHNetHelper qh_requestGET:URLString parameters:parameters success:^(NSNumber *code, NSString *message, NSDictionary *data) {
                [rootView.qh_quoteButton setTitle:@"重新报价" forState:0];
                [self showToastWithText:message];
            } failure:^(NSError *error) {
                
                NSString *errorString = [NSString stringWithFormat:@"网络出错:%@,code:%ld", error.domain, (long)error.code];
                [self showToastWithText:errorString];
            }];
        }
    } completion:nil];
}

#pragma mark --Setter

#pragma mark --Getter

#pragma mark --View

@end
